import Vue from 'vue'
import Router from 'vue-router'
import db from '../utils/localstorage'
import Layout from '@/View/meus/index'
import request from '../network/request'
import pigView from '@/Layout/pigView'
import store from '../store'

Vue.use(Router)

const originalPush = Router.prototype.push
// 修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const constRouter = [
  // 可以通过route.replace（{/redirect + path}） 处理不刷新页面情况下刷新数据
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path*',
        component: (resolve) => require(['@/View/redirect/index'], resolve)
      }
    ]
  },
  {
    path: '/login',
    name: '登录',
    component: (resolve) => require(['@/View/login/index'], resolve)
  },
  {
    path: '*',
    component: (resolve) => require(['@/View/error-page/404'], resolve),
    hidden: true
  },
  {
    path: '/',
    name: '首页',
    redirect: '/home',
    component: Layout,
    children: [
      {
        path: '/home',
        ico: 'el-icon-s-home',
        name: '首页',
        affix: true,
        component: (resolve) => require(['@/View/homePage/index'], resolve) },
      {
        path: '/video',
        ico: 'el-icon-s-home',
        name: '视频播放',
        affix: true,
        component: (resolve) => require(['@/components/DHPlayer/demo'], resolve) }
    ]
  }
]
const router = new Router({
  scrollBehavior: () => ({ y: 0 }),
  routes: constRouter
})
var WhiteList = ['/login']
let asyRoute
router.beforeEach((to, from, next) => {
  //  判断路由是否去往白名单
  if (WhiteList.indexOf(to.path) !== -1) {
    next()
  } else {
    // db.save('USER_ROUTER', '{name: "关于", path: "/"}, component: "/View/regard/index"')
    const token = db.get('TOKEN')
    const Route = db.get('USER_ROUTER')
    if (token.length) {
      if (!asyRoute) {
        if (Object.keys(Route).length === 0) {
          //   没有就动态添加路由
          request.get('user/route').then(res => {
            const newData = res.data.data
            const asyncRouter = newData.route
            const pres = newData.pres
            store.commit('getter/setRoutes', asyncRouter)
            store.commit('getter/setPres', pres)
            asyRoute = asyncRouter
            go(to, next)
          })
        } else {
          asyRoute = Route
          go(to, next)
        }
      } else {
        next()
      }
    } else {
      next('/login')
    }
  }
})
function addRoute(route) {
  return route.filter(t => {
    const component = t.component
    if (component) {
      if (t.component === 'pigView') {
        t.component = pigView
      } else {
        t.component = path(component)
      }
      if (t.children && t.children.length) {
        t.children = addRoute(t.children)
      }
    }
    return true
  })
}
function go(to, next) {
  // TODO: 3为首页在数组里面的位置
  Vue.set(constRouter[3], 'children', addRoute(asyRoute))
  router.addRoutes(constRouter)
  // 路由在add后可能不会执行next 需要以下写法
  next({ ...to, replace: true })
}

// 动态请求路径
function path(path) {
  return (resolve) => require([`@/View${path}.vue`], resolve)
}

export default router
